<?php

namespace App\Http\Requests;

use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Contracts\Validation\Validator;

trait RequestTrait
{
    /**
     * Set custom messages for validator errors.
     *
     * @return array
     */
    public function messages()
    {
        return [
            'required' => "':attribute'是必须的",
            'integer' => "':attribute'必须是整数",
            'numeric' => "':attribute'必须是数字",
            'in' => "':attribute'必须是[:values]其中之一",
            'digits' => "':attribute'必须是数字且长度为:value",
            'json' => "':attribute'必须是json格式",
            'array' => "':attribute'必须是数组格式",
            'date_format' => "':attribute'必须是:format的日期格式",
        ];
    }

    /**
     * 自定义错误格式
     *
     * @author Vance
     *
     * @param Validator $validator
     * @return array
     */
    protected function formatErrors(Validator $validator)
    {
        return [
            'message' => $validator->errors()->first(),
            'status_code' => 422,
        ];
    }

    /**
     * 自定义验证失败格式
     *
     * @author Vance
     *
     * @param Validator $validator
     * @param int $code
     */
    protected function failedValidation(Validator $validator, $code = 0)
    {
        $statusCode = 422; // Http状态码

        throw new HttpException($statusCode, $validator->errors()->first(), null, [], $code);
    }

    /**
     * 返回系统验证错误信息(需在语言包定义对应错误信息)
     *
     * @author Vance
     *
     * @param string $prefix
     * @return array
     */
    protected function createMessages($prefix = '')
    {
        $messages = [];

        $prefix = trim($prefix, '.') . '.';

        foreach ($this->rules() as $field => $rule) {
            if (!is_array($rule)) {
                $rule = explode('|', $rule);
            }

            foreach ($rule as $r) {
                $k = explode(':', $r)[0];
                $validate = "{$field}.{$k}";
                $messages[$validate] = trans($prefix . $validate);
            }
        }

        return $messages;
    }
}